import config from "../config.js"
import util from "./util.js"

const network = {
	//post请求
	post: (url, params, success, failed) => {
		uni.request({
			url: `${config.host}${url}`,
			method: "POST",
			header: {},
			data: params,
			success: (res) => {
				if (res.data.code != 200) {
					!failed && util.toast(res.data.msg)
					failed && failed(res.data)
				} else {
					success && success(res.data)
				}
			},
			fail: (res) => {
				uni.hideLoading();
				if (failed) {
					failed(res.data)
				} else {
					util.toast("网络错误，请检查后重试")
				}
			}
		})
	},
	//get请求
	get: (url, params, success, failed) => {
		uni.request({
			url: `${config.host}${url}`,
			method: "GET",
			header: {},
			data: params,
			success: res => {
				//设置当前时间
				reslove(res.data);
				if (res.data.code != 200) {
					!failed && util.toast(res.data.msg)
					failed && failed(res.data)
				} else {
					success && success(res.data)
				}
			},
			fail: (res) => {
				uni.hideLoading();
				if (failed) {
					failed(res.data)
				} else {
					util.toast("网络错误，请检查后重试")
				}
			}
		})
	},
	put: (url, params, success, failed) => {
		uni.request({
			url: `${config.host}${url}`,
			method: "PUT",
			header: {},
			data: params,
			success: res => {
				reslove(res.data);
				if (res.data.code != 200) {
					!failed && util.toast(res.data.msg)
					failed && failed()
				} else {
					success && success(res.data)
				}
			},
			fail: (res) => {
				uni.hideLoading();
				if (failed) {
					failed(res.data)
				} else {
					util.toast("网络错误，请检查后重试")
				}
			}
		})
	},
	delete: (url, params, success, failed) => {
		uni.request({
			url: `${config.host}${url}`,
			method: "DELETE",
			header: {
				// 'Content-Type':"application/x-www-form-urlencoded"
			},
			data: params,
			success: res => {
				reslove(res.data);
				if (res.data.code != 200) {
					!failed && util.toast(res.data.msg)
					failed && failed(res.data)
				} else {
					success && success(res.data)
				}
			},
			fail: (res) => {
				uni.hideLoading();
				if (failed) {
					failed(res.data)
				} else {
					util.toast("网络错误，请检查后重试")
				}
			}
		})
	},
}

//请求返回拦截
const reslove = function(res) {
	if (res.code == 401) {
		uni.clearStorage();
		uni.reLaunch({
			url: '/pages/login/login',
		})
		return
	}
}

export default network
